﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using xiapibuy_collect.entity;
using xiapibuy_collect.utils;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace xiapibuy_collect.Controllers
{
    [Route("api/shop")]
    public class ShopController : Controller
    {


        // 根据关键字查询 商铺 根据商铺数量排序 降序
        [HttpGet("{kw},{count}")]
        [Route("shoplist")]
        public async Task<List<ShopBase>> GetAsync(String kw, int count)
        {
            var url = "search_users/?keyword=" + kw + "&limit=6&offset=0&page=search_user&with_search_cover=true";
            List<ShopBase> shopList = new List<ShopBase>();

            //需要遍历10页查询
            for (int i = 0; i < 10; i++)
            {
                var str = await HttpClientKit.ReadWithAngleSharpAsync("search_users/?keyword=" + kw + "&limit=6&offset=" + i + "&page=search_user&with_search_cover=true").ConfigureAwait(false);
                if (str == null)
                {
                    Console.WriteLine("网络请求失败");
                    break;
                }
                JObject root = JObject.Parse(str);
                if (root == null || root["data"] == null)
                {
                    Console.WriteLine("数据访问异常");
                    break;
                }
                var data = root["data"];
                var use = data["users"].ToString();
                var total_count = data.Value<int>("total_count");

                JArray array = JArray.Parse(use);
                for (int k = 0; k < array.Count; k++)
                {
                    JObject s = JObject.Parse(array[k].ToString());
                    shopList.Add(new ShopBase(s.Value<int>("shopid"), s.Value<string>("shopname"), s.Value<int>("products"), s.Value<double>("shop_rating"), s.Value<int>("response_rate")));
                }
                //如果是最后一页就跳出循环
                if (total_count / 6 == i)
                {
                    break;
                }
            }
            if (count > 0)
            {
                shopList = shopList.Where(s => s.productCount >= count).ToList();
            }
            shopList = shopList.OrderBy(s => -s.productCount).ToList();
            Console.WriteLine(JObject.FromObject(shopList).ToString());
            return shopList;
        }



        // POST api/<controller>
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
